package me.zhengjie.modules.quartz.task;

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.property.domain.Money;
import me.zhengjie.modules.property.repository.MoneyRepository;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;

@Slf4j
@Service
public class GetDataToHead {

    @Resource
    private MoneyRepository moneyRepository;

    @Resource
    private RabbitTemplate rabbitmqTemplate;

    public void run() {
        try {
            List<Map<String, Object>> dailyData = calculateDailyData(); // 修改为按日计算
            rabbitmqTemplate.convertAndSend("GetDataToHead", new Gson().toJson(dailyData));
        } catch (Exception e) {
            log.error("Error sending data to RabbitMQ: {}", e.getMessage(), e);
        }
    }

    // 计算每天的总和及其与前一天的差值
    public List<Map<String, Object>> calculateDailyData() {
        List<Money> moneyList = moneyRepository.findAllOrdered(); // 获取所有记录
        Map<LocalDate, BigDecimal> dailySums = new TreeMap<>(Comparator.reverseOrder());  // 每天总和

        // 遍历所有 Money 记录
        for (Money money : moneyList) {
            LocalDate createDate = money.getCreateTime().toLocalDateTime().toLocalDate();

            // 计算每天的总和
            dailySums.put(createDate, dailySums.getOrDefault(createDate, BigDecimal.ZERO).add(calculateSum(money)));
        }

        // 计算每天与前一天的差值
        List<Map<String, Object>> result = new ArrayList<>();
        LocalDate[] days = dailySums.keySet().toArray(new LocalDate[0]); // 将key转为数组，按倒序排列

        for (int i = 0; i < days.length; i++) {
            BigDecimal currentDaySum = dailySums.get(days[i]);
            BigDecimal difference = BigDecimal.ZERO;

            // 如果有前一天，计算差值，否则差值就是当前天的总和
            if (i < days.length - 1) {
                BigDecimal nextDaySum = dailySums.get(days[i + 1]);
                difference = currentDaySum.subtract(nextDaySum); // 当前天减去前一天
            }

            // 构建结果数据
            Map<String, Object> data = new HashMap<>();
            data.put("date", days[i].toString()); // 使用日期
            data.put("currentDaySum", currentDaySum);
            data.put("difference", difference);

            result.add(data);
        }

        return result;
    }

    // 计算单条记录的总和，处理 varchar 类型字段
    private BigDecimal calculateSum(Money money) {
        BigDecimal card = convertToBigDecimal(money.getCard());
        BigDecimal wx = convertToBigDecimal(money.getWx());
        BigDecimal pay = convertToBigDecimal(money.getPay());
        BigDecimal lend = convertToBigDecimal(money.getLend());
        BigDecimal bond = convertToBigDecimal(money.getBond());

        return card.add(wx).add(pay).add(lend).add(bond); // 求和
    }

    // 将 varchar 类型转换为 BigDecimal，如果为空或非数字则返回 0
    private BigDecimal convertToBigDecimal(String value) {
        try {
            return new BigDecimal(value); // 尝试将字符串转换为 BigDecimal
        } catch (NumberFormatException e) {
            return BigDecimal.ZERO; // 如果转换失败，返回 0
        }
    }
}